package com.alienlab.finder.service.impl;

import com.alienlab.finder.domain.AppUser;
import com.alienlab.finder.domain.CheckTask;
import com.alienlab.finder.repository.AppUserRepository;
import com.alienlab.finder.repository.CheckTaskRepository;
import com.alienlab.finder.repository.RelationshipRepository;
import com.alienlab.finder.service.WarningService;
import com.alienlab.finder.domain.Warning;
import com.alienlab.finder.repository.WarningRepository;
import com.alienlab.finder.service.dto.WarningDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * Service Implementation for managing Warning.
 */
@Service
@Transactional
public class WarningServiceImpl implements WarningService {

    private final Logger log = LoggerFactory.getLogger(WarningServiceImpl.class);

    private final WarningRepository warningRepository;
    private final CheckTaskRepository checkTaskRepository;
    private final AppUserRepository appUserRepository;
    private final RelationshipRepository relationshipRepository;

    public WarningServiceImpl(RelationshipRepository relationshipRepository,WarningRepository warningRepository,CheckTaskRepository checkTaskRepository,AppUserRepository appUserRepository) {
        this.warningRepository = warningRepository;
        this.checkTaskRepository = checkTaskRepository;
        this.appUserRepository = appUserRepository;
        this.relationshipRepository = relationshipRepository;
    }

    /**
     * Save a warning.
     *
     * @param warning the entity to save
     * @return the persisted entity
     */
    @Override
    public Warning save(Warning warning) {
        log.debug("Request to save Warning : {}", warning);
        return warningRepository.save(warning);
    }

    /**
     * Get all the warnings.
     *
     * @param pageable the pagination information
     * @return the list of entities
     */
    @Override
    @Transactional(readOnly = true)
    public Page<Warning> findAll(Pageable pageable) {
        log.debug("Request to get all Warnings");
        return warningRepository.findAll(pageable);
    }


    /**
     * Get one warning by id.
     *
     * @param id the id of the entity
     * @return the entity
     */
    @Override
    @Transactional(readOnly = true)
    public Optional<Warning> findOne(Long id) {
        log.debug("Request to get Warning : {}", id);
        return warningRepository.findById(id);
    }

    /**
     * Delete the warning by id.
     *
     * @param id the id of the entity
     */
    @Override
    public void delete(Long id) {
        log.debug("Request to delete Warning : {}", id);
        warningRepository.deleteById(id);
    }

    @Override
    public Warning addWarning(String admin_open_id, String guest_open_id, String desc) throws Exception {
        if ("".equals(admin_open_id) || admin_open_id==null){

            throw  new Exception("未获取admin_open_id");
        }
        if ("".equals(guest_open_id) || guest_open_id==null){

            throw  new Exception("未获取guest_open_id");
        }
        if ("".equals(desc) || desc==null){

            throw  new Exception("未获取本次警告的描述信息desc");
        }
        Warning warning = new Warning();
        warning.setAdminOpenId(admin_open_id);
        warning.setGuestOpenId(guest_open_id);
        warning.setDescription(desc);
        warning.setTime(ZonedDateTime.now());
        warning.setReadflag("0");
        warning = warningRepository.save(warning);
        return warning;
    }

    @Override
    public Warning updateWarning(Long warning_id, String desc) throws Exception {
        if (0==warning_id || warning_id==null){
            throw new Exception("未获取到本次需要修改警告信息的id");
        }
        Warning warning = warningRepository.findById(warning_id).orElse(null);
        if (warning!=null){
            warning.setTime(ZonedDateTime.now());
            warning.setDescription(desc);
            warning = warningRepository.save(warning);
            return  warning;
        }else{
            throw new Exception("未查到id为:"+warning_id+"的警告信息，不可进行修改操作");
        }

    }

    @Override
    public WarningDTO getWarningMessageByTaskId(String taskId) throws Exception {

        CheckTask checkTask = checkTaskRepository.findById(Long.valueOf(taskId)).orElse(null);
        if (checkTask==null){
            throw  new Exception("未查到id为:"+taskId+"的监控任务，不可进行操作");
        }else {

            String openId= checkTask.getGuestOpenId();
            String headImage =  appUserRepository.findByOpenId(openId).getHeadimage();
            String name = relationshipRepository.findByMainUserOpenIdAndAndSecondUserOpenId(checkTask.getAdminOpenId(),checkTask.getGuestOpenId()).getNickname();
            if ("".equals(name) || name ==null){
                name = appUserRepository.findByOpenId(openId).getWechatname();
            }
            String message = "";
            String readflag = "0";
            String warningid="";
            Warning warning = warningRepository.findById(checkTask.getWarningId()).orElse(null);
            if (warning !=null ){
                message = warning.getDescription();
                readflag = warning.getReadflag();
                warningid = checkTask.getWarningId().toString();
            }

            WarningDTO warningDTO =new WarningDTO();
            warningDTO.setTaskid(taskId);
            warningDTO.setName(name);
            warningDTO.setOpenid(openId);
            warningDTO.setHeadimage(headImage);
            warningDTO.setMessage(message);
            warningDTO.setReadflag(readflag);
            warningDTO.setWarningid(warningid);
            return  warningDTO;

        }

    }

    @Override
    public List<WarningDTO> getWarningList(String admin_open_id) throws Exception {

        if ("".equals(admin_open_id) || admin_open_id==null){

            throw  new Exception("未获取admin_open_id");
        }
        AppUser main_appUser = appUserRepository.findByOpenId(admin_open_id);
        if (main_appUser==null){
            throw new Exception("未查找到opden_id为:"+admin_open_id+"的用户");
        }
        List<WarningDTO> warningDTOList = new ArrayList<>();
        List<CheckTask> checkTaskList = checkTaskRepository.findByAdminOpenIdOrderByStartTimeDesc(admin_open_id);
        if (checkTaskList.size()>0){
            for (int i = 0; i < checkTaskList.size(); i++) {
                CheckTask checkTask = checkTaskList.get(i);
                if(checkTask.getWarningId()!=null){
                    Warning warning = warningRepository.findById(checkTask.getWarningId()).orElse(null);
                    if (warning != null) {
                        String warningid = checkTask.getWarningId().toString();
                        String openId= checkTask.getGuestOpenId();
                        String headImage =  appUserRepository.findByOpenId(openId).getHeadimage();
                        String name = relationshipRepository.findByMainUserOpenIdAndAndSecondUserOpenId(checkTask.getAdminOpenId(),checkTask.getGuestOpenId()).getNickname();
                        if ("".equals(name) || name ==null){
                            name = appUserRepository.findByOpenId(openId).getWechatname();
                        }
                        WarningDTO warningDTO =new WarningDTO();
                        warningDTO.setTaskid(String.valueOf(checkTask.getId()));
                        warningDTO.setName(name);
                        warningDTO.setOpenid(openId);
                        warningDTO.setHeadimage(headImage);
                        warningDTO.setMessage(warning.getDescription());
                        warningDTO.setReadflag(warning.getReadflag());
                        warningDTO.setWarningid(warningid);
                        warningDTOList.add(warningDTO);
                    }
                }

            }
        }




        return warningDTOList;
    }

    @Override
    public Warning modifyReadState(Long warning_id) throws Exception {
        if (0==warning_id || warning_id==null){
            throw new Exception("未获取到本次需要修改警告信息的id");
        }
        Warning warning = warningRepository.findById(warning_id).orElse(null);
        if (warning!=null){
            warning.setTime(ZonedDateTime.now());
            warning.setReadflag("1");
            warning = warningRepository.save(warning);
            return  warning;
        }else{
            throw new Exception("未查到id为:"+warning_id+"的警告信息，不可进行修改操作");
        }
    }
}
